use:lazyImage

Posted on 2023-04-20 by

henrikvilhelmberglund

Here we're going to use an action to only load an image when it's in the viewport. We could try to reuse the use:viewport action , but it's in a .js file instead of a .svelte file.

Let's try to make it work.

lazy image demo

Hello world!

<script>
	import viewport from "./useViewportAction";
	import lazyImage from "./lazyImageAction";
	import { base } from "$app/paths";
</script>

<div style="height: 200px; background: red;" />
<div style="height: 200px; background: blue;" />
<div style="height: 200px; background: green;" />

<img use:lazyImage data-src="{base}/Henrik.png" alt="lazy image demo" />
<h1
	use:viewport
	on:enterViewport={() => console.log("entered viewport")}
	on:exitViewport={() => console.log("exited viewport")}>
	Hello world!
</h1>

<div style="height: 200px; background: red;" />
<div style="height: 200px; background: blue;" />
<div style="height: 200px; background: green;" />

<style>
</style>

If we want to use an action in a .js file we can just simply run the function (here with a variable reference to it as well).

Since we could reuse our old action it was very easy. We simply import our old action and add new event listeners for the events created in the old action.

We put a data-src attribute in the img tag instead of a src one to prevent it from loading when the page loads.